package com.example.gate.websocket;

import com.example.game.CReq;
import com.example.game.CResp;
import com.example.common.constants.ServiceNames;
import com.example.common.grpc.DynamicGrpcClientManager;
import com.example.game.proto.internal.SrvReq;
import com.example.game.proto.internal.SrvResp;
import com.google.protobuf.ByteString;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * WebSocket服务器
 * 支持M0Base.proto协议
 * 
 * @author: Allen
 * @create: 2025/1/27 14:00
 * @description: WebSocket服务器
 **/
@Slf4j
@Component
public class WebSocketServer {
    
    @Value("${gate.websocket.port:8001}")
    private int wsPort;
    
    @Value("${gate.websocket.path:/ws}")
    private String wsPath;
    
    @Value("${gate.websocket.boss.threads:1}")
    private int bossThreads;
    
    @Value("${gate.websocket.worker.threads:4}")
    private int workerThreads;
    
    @Autowired
    private WebSocketMessageHandler webSocketMessageHandler;
    
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private Channel serverChannel;
    
    @PostConstruct
    public void start() throws Exception {
        log.info("启动WebSocket服务器，端口: {}, 路径: {}", wsPort, wsPath);
        
        bossGroup = new NioEventLoopGroup(bossThreads);
        workerGroup = new NioEventLoopGroup(workerThreads);
        
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            
                            // HTTP编解码器
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new ChunkedWriteHandler());
                            pipeline.addLast(new HttpObjectAggregator(65536));
                            
                            // WebSocket协议处理器
                            pipeline.addLast(new WebSocketServerProtocolHandler(wsPath, null, true));
                            pipeline.addLast(new WSClientProtobufDecoder());
                            pipeline.addLast(new WSClientProtobufEncoder());

                            // 自定义WebSocket消息处理器
                            pipeline.addLast(webSocketMessageHandler);
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            
            ChannelFuture future = bootstrap.bind(wsPort).sync();
            serverChannel = future.channel();
            
            log.info("WebSocket服务器启动成功，监听端口: {}", wsPort);
            
        } catch (Exception e) {
            log.error("WebSocket服务器启动失败", e);
            throw e;
        }
    }
    
    @PreDestroy
    public void stop() {
        log.info("关闭WebSocket服务器");
        
        if (serverChannel != null) {
            serverChannel.close();
        }
        
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        
        log.info("WebSocket服务器已关闭");
    }
} 